package org.fujie.plugin.cloud.core.provider.factory;

import org.fujie.plugin.cloud.comm.exception.IdCardScanException;
import org.fujie.plugin.cloud.core.provider.config.BaseConfig;
import org.fujie.plugin.cloud.core.provider.service.BaseIdCardService;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author slm
 * @description 工厂持有者类，用于注册和获取抽象工厂实例。
 */
public class FactoryHolder {

    private static final Map<String, BaseFactory<? extends BaseIdCardService, ? extends BaseConfig>> factories = new ConcurrentHashMap<>();

    private static final String ERROR_MESSAGE_TEMPLATE = "服务商:%s,实例不存在,请检查配置文件";

    /**
     * 注册工厂
     *
     * @param factory 需要注册的工厂
     * @throws IdCardScanException 如果工厂为null或其他问题
     */
    public static void registerFactory(BaseFactory<? extends BaseIdCardService, ? extends BaseConfig> factory) {
        if (factory == null) {
            throw new IdCardScanException().setMessage(ERROR_MESSAGE_TEMPLATE.formatted("UNKNOWN"));
        }
        factories.put(factory.getSupplier(), factory);
    }

    /**
     * 根据供应商获取工厂
     *
     * @param supplier 供应商的关键字
     * @return 对应的工厂
     * @throws IdCardScanException 如果供应商没有关联的工厂
     */
    public static BaseFactory<? extends BaseIdCardService, ? extends BaseConfig> getFactory(String supplier) {
        return Optional.ofNullable(factories.get(supplier))
                .orElseThrow(() -> new IdCardScanException().setMessage(ERROR_MESSAGE_TEMPLATE.formatted(supplier)));
    }


}
